package cz.mff.kusad5am.hb.ws;

import java.util.List;

import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;
import org.springframework.ws.server.endpoint.AbstractJDomPayloadEndpoint;

import cz.mff.kusad5am.hb.schema.list.Hostel;
import cz.mff.kusad5am.hb.schema.reservationlist.HostelReservation;
import cz.mff.kusad5am.hb.schema.roomlist.RoomType;
import cz.mff.kusad5am.hb.service.ListOfRoomsWorker;
import cz.mff.kusad5am.hb.service.ReservationWorker;

public class ListOfReservationEndpoint extends AbstractJDomPayloadEndpoint {

	private final ReservationWorker worker;
	
	public ListOfReservationEndpoint(ReservationWorker worker) {
		this.worker = worker;
	}
	
	
	@Override
	protected Element invokeInternal(Element requestElement) throws Exception {
		
		Namespace ns = requestElement.getNamespace();
		String nsp = ns.getPrefix();
		String custId = XPath.newInstance("//"+nsp+":ReservationListRequest/@id").valueOf(requestElement);
		List<HostelReservation> list = worker.getListOfReservation(Integer.parseInt(custId));
		Element response = createResponse(list, ns);
		return response;
	}
	
	private Element createResponse(List<HostelReservation> list, Namespace tns) {
		Element response = new Element("ReservationListResponse");
		response.setNamespace(tns);
		
		for (HostelReservation rv: list) {
			Element r = new Element("HostelReservation");
			r.setNamespace(tns);
			r.setAttribute("arrivalDate", "2009-10-12");
			r.setAttribute("numberOfGuests", new Integer(rv.getNumberOfGuests()).toString());
			r.setAttribute("numberOfNights", new Integer(rv.getNumerOfNights()).toString());
			r.setAttribute("FinalPrice", rv.getFinalPrice());
			r.setAttribute("ReservationStatus", rv.getReservationStatus());
			r.setAttribute("id", new Integer(rv.getId()).toString());

			Element h = new Element("Hostel");
			h.setNamespace(tns);
			h.setAttribute("name", rv.getHostel().getName());
			h.setAttribute("id", new Integer(rv.getHostel().getId()).toString());
			h.setAttribute("Country", rv.getHostel().getCountry());
			h.setAttribute("City", rv.getHostel().getCity());
			h.setAttribute("Address", rv.getHostel().getAddress());
			h.setAttribute("ZipCode", rv.getHostel().getZipCode());
			
			r.setContent(h);
			response.addContent(r);
		}
		return response;
	}
}
